package org.example.mygobang.api;

import com.google.code.kaptcha.Constants;
import org.example.mygobang.model.User;
import org.example.mygobang.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
public class UserAPI {
    private final static long VALID_MILLIS_TIME = 60 * 1000;

    @Autowired
    private UserMapper userMapper;

    //设置时间问60s

    @RequestMapping("/login")
    public Object login(String username,String password,String captcha,HttpServletRequest httpServletRequest) {
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)) {
            System.out.println("登录失败");
            return new User();
        }
        HttpSession httpSession = httpServletRequest.getSession(true);
        httpSession.setAttribute("user", user);
        if (!StringUtils.hasLength(captcha)) {
            return new User();
        }
        //获取验证码
        String savedCaptcha = (String) httpSession.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //获取验证生成时间
        Date sessionDate = (Date) httpSession.getAttribute(Constants.KAPTCHA_SESSION_DATE);
        if (captcha.equalsIgnoreCase(savedCaptcha)) {
            if (sessionDate == null || System.currentTimeMillis() - sessionDate.getTime() < VALID_MILLIS_TIME)
                return user;
        }
        return new User();
    }
    @RequestMapping("/register")
    public Object register(String username,String password) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            User user = new User();
            return user;
        }
    }
    @RequestMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest httpServletRequest) {
        try {
            HttpSession httpSession = httpServletRequest.getSession(false);
            User user = (User) httpSession.getAttribute("user");
            // 拿着这个 user 对象, 去数据库中找, 找到最新的数据
            User newuser = userMapper.selectByName(user.getUsername());
            return newuser;
        } catch (NullPointerException e) {
            return new User();
        }
    }
    public Object getHistroy(HttpServletRequest httpServletRequest) {
        return httpServletRequest;
    }
}
